package appcus

import (
	"counter-help/admin/server/global"
	customerReq "counter-help/admin/server/model/app/request"
	"counter-help/admin/server/model/common/response"
	"counter-help/admin/server/model/customer"
	"counter-help/admin/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type CusOrderApi struct{}

func (cusOrderApi *CusOrderApi) CreateCusOrder(c *gin.Context) {
	userID := int(utils.GetUserID(c))

	// 绑定 JSON 参数
	var cusOrder customerReq.CreateCusOrder
	if err := c.ShouldBind(&cusOrder); err != nil {
		response.FailWithMessage("参数解析失败: "+err.Error(), c)
		return
	}
	// 检查用户认证信息
	missingCertifications := checkUserCertifications(userID, "Orders")

	if len(missingCertifications) > 0 {
		var detailedMessage string
		for _, certMessage := range missingCertifications {
			// 生成更详细的消息
			detailedMessage += certMessage + ";"
		}

		// 移除最后一个分号
		if len(detailedMessage) > 0 {
			detailedMessage = detailedMessage[:len(detailedMessage)-1]
		}

		// 提供详细的提示信息
		response.CommonFailWithMessage("请先完成以下认证："+detailedMessage, c)
		return
	}
	// 获取文件字段，允许文件未上传
	file, fileHeader, err := c.Request.FormFile("attach")
	if err != nil {
		file = nil // 表示未上传文件
		fileHeader = nil
	} else {
		defer file.Close() // 确保文件被关闭
	}

	// 调用服务层创建订单
	if err := cusOrderService.CreateCusOrder(userID, &cusOrder, fileHeader, c); err != nil {
		response.FailWithMessage("创建订单失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("订单创建成功", c)
}

func (cusOrderApi *CusOrderApi) DeleteCusOrder(c *gin.Context) {
	ID := c.Param("ID") // 改为使用路径参数
	err := cusOrderService.DeleteCusOrder(ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

func (cusOrderApi *CusOrderApi) DeleteCusOrderByIds(c *gin.Context) {
	IDs := c.QueryArray("IDs[]")
	err := cusOrderService.DeleteCusOrderByIds(IDs)
	if err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

func (cusOrderApi *CusOrderApi) UpdateCusOrder(c *gin.Context) {
	var cusOrder customer.CusOrder
	err := c.ShouldBindJSON(&cusOrder)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = cusOrderService.UpdateCusOrder(cusOrder)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

func (cusOrderApi *CusOrderApi) FindCusOrder(c *gin.Context) {
	ID := c.Query("ID")
	if ID == "" {
		response.FailWithMessage("参数ID不能为空", c)
		return
	}
	recusOrder, err := cusOrderService.GetCusOrderByID(ID)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(recusOrder, c)
}

func (cusOrderApi *CusOrderApi) GetCusOrderList(c *gin.Context) {
	var pageInfo customerReq.CusOrderSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := cusOrderService.GetCusOrderInfoList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

func (cusOrderApi *CusOrderApi) GetCusOrderPublic(c *gin.Context) {
	// 此接口不需要鉴权
	// 示例为返回了一个固定的消息接口，一般本接口用于C端服务，需要自己实现业务逻辑
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的cusOrder表接口信息",
	}, "获取成功", c)
}

func (cusOrderApi *CusOrderApi) GetAllCusOrders(c *gin.Context) {
	list, err := cusOrderService.GetAllCusOrders()
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(list, "获取成功", c)
}
func (cusOrderApi *CusOrderApi) GetOptimalCusOrders(c *gin.Context) {
	list, err := cusOrderService.GetOptimalCusOrders()
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(list, "获取成功", c)
}

// GetCusOrdersByUserID 获取用户发布的订单
func (cusOrderApi *CusOrderApi) GetCusOrdersByUserID(c *gin.Context) {
	userID := int(utils.GetUserID(c))
	if userID == 0 {
		response.FailWithMessage("用户失效，请重新登录", c)
		return
	}
	// 定义结构体接收 JSON 请求体中的参数
	type RequestParams struct {
		SortBy   string `json:"sort_by"`  // 排序参数
		QueryStr string `json:"queryStr"` // 查询条件
		Status   int    `json:"status"`   // 查询条件
	}

	// 解析 JSON 请求体
	var params RequestParams
	if err := c.ShouldBindJSON(&params); err != nil {
		response.FailWithMessage("参数解析失败: "+err.Error(), c)
		return
	}

	// 调用服务层方法获取订单
	orders, err := cusOrderService.GetOrdersByUserID(userID, params.SortBy, params.QueryStr, params.Status)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败: "+err.Error(), c)
		return
	}
	response.OkWithDetailed(orders, "获取成功", c)
}

func (cusOrderApi *CusOrderApi) FilterCusOrders(c *gin.Context) {
	var searchParams customerReq.SearchParams
	if err := c.ShouldBindJSON(&searchParams); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userID := int(utils.GetUserID(c))
	list, total, err := cusOrderService.FilterCusOrderList(userID, searchParams)
	if err != nil {
		global.GVA_LOG.Error("筛选失败!", zap.Error(err))
		response.FailWithMessage("筛选失败:"+err.Error(), c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     searchParams.Page,
		PageSize: searchParams.PageSize,
	}, "筛选成功", c)
}

func (cusOrderApi *CusOrderApi) SearchOrders(c *gin.Context) {
	var searchParams struct {
		QueryStr string `json:"queryStr" binding:"required"`
		Page     int    `json:"page" form:"page"`
		PageSize int    `json:"page_size" form:"page_size"`
	}

	// 解析前端传来的 JSON 请求数据
	if err := c.ShouldBindJSON(&searchParams); err != nil {
		response.FailWithMessage("查询参数解析失败:"+err.Error(), c)
		return
	}
	userID := int(utils.GetUserID(c))

	list, total, err := cusOrderService.SearchOrders(userID, searchParams.QueryStr)
	if err != nil {
		global.GVA_LOG.Error("筛选失败!", zap.Error(err))
		response.FailWithMessage("筛选失败:"+err.Error(), c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     searchParams.Page,
		PageSize: searchParams.PageSize,
	}, "筛选成功", c)
}

func (cusOrderApi *CusOrderApi) GetCusOrdersByStatusAndIsPaid(c *gin.Context) {
	var filterParams customerReq.CusOrderFilterParams
	err := c.BindJSON(&filterParams)
	if err != nil {
		global.GVA_LOG.Error("参数解析失败 Error::" + err.Error())
		response.FailWithMessage("参数解析失败:"+err.Error(), c)
		return
	}

	// 从前端获取 SortBy 和 QueryStr 参数
	sortBy := filterParams.SortBy
	queryStr := filterParams.QueryStr
	userID := int(utils.GetUserID(c))
	//fmt.Println(filterParams.IsPaid)
	// 调用 service 获取符合条件的订单
	orders, err := cusOrderService.GetCusOrdersByStatusAndIsPaid(userID, filterParams.Status, filterParams.IsPaid, sortBy, queryStr)
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(orders, "获取成功", c)
}

func (cusOrderApi *CusOrderApi) SearchCusOrders(c *gin.Context) {
	var searchParams struct {
		QueryStr string `json:"queryStr" binding:"required"`
	}

	// 解析前端传来的 JSON 请求数据
	if err := c.ShouldBindJSON(&searchParams); err != nil {
		response.FailWithMessage("查询参数解析失败:"+err.Error(), c)
		return
	}

	// 调用 Service 执行模糊查询
	orders, err := cusOrderService.SearchCusOrdersByAnRequire(searchParams.QueryStr)
	if err != nil {
		global.GVA_LOG.Error("模糊查询失败!", zap.Error(err))
		response.FailWithMessage("模糊查询失败:"+err.Error(), c)
		return
	}

	response.OkWithDetailed(orders, "模糊查询成功", c)
}

// EvaluateCusOrder 创建订单评价
func (cusOrderApi *CusOrderApi) EvaluateCusOrder(c *gin.Context) {
	var evaluationParams struct {
		OrderID  int    `json:"order_id" binding:"required"`
		OrderEva string `json:"order_eva" binding:"required"`
	}

	// 解析前端传递的 JSON 请求数据
	if err := c.ShouldBindJSON(&evaluationParams); err != nil {
		response.FailWithMessage("评价参数解析失败:"+err.Error(), c)
		return
	}

	// 调用 Service 执行订单评价更新
	err := cusOrderService.UpdateOrderEvaluation(evaluationParams.OrderID, evaluationParams.OrderEva)
	if err != nil {
		global.GVA_LOG.Error("评价失败!", zap.Error(err))
		response.FailWithMessage("评价失败:"+err.Error(), c)
		return
	}

	response.OkWithMessage("评价成功", c)
}

// GetEvaluatedCusOrders 获取订单评价
func (cusOrderApi *CusOrderApi) GetEvaluatedCusOrders(c *gin.Context) {
	// 调用 Service 获取含有评价的订单列表
	orders, err := cusOrderService.GetEvaluatedOrders()
	if err != nil {
		global.GVA_LOG.Error("获取含有评价的订单失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}

	response.OkWithDetailed(orders, "获取成功", c)
}
